package com.sxyjhh.daqc_dbutils.mongodb;

import com.mongodb.Block;
import com.mongodb.MongoClient;
import com.mongodb.client.FindIterable;
import com.mongodb.client.MongoCollection;
import com.mongodb.client.MongoDatabase;
import org.bson.Document;

/**
 * Description:
 *
 * @JDK Version:1.8.0_40
 * Version: V1.0
 * Author: spring
 * Date: 2016/10/12
 */
public class CudExample {

    public static void main(String[] args) {
        MongoClient mongoClient = new MongoClient("192.168.0.160", 27017);
        MongoDatabase database = mongoClient.getDatabase("lesson");

        CudExample client = new CudExample(database);
        client.show();
        mongoClient.close();
    }

    private MongoDatabase database;

    public CudExample(MongoDatabase database) {
        this.database = database;
    }

    public void show() {
        MongoCollection<Document> mc = database.getCollection("language");
        //每次执行前清空集合以方便重复运行
        mc.drop();

        mc.insertOne(new Document("oop", "java"));
        printCollection("insert java", mc);
    }

    //打印查询的结果集
    public void printCollection(String doing, MongoCollection<Document> mc) {
        System.out.println(doing);
        FindIterable<Document> iterable = mc.find();
        iterable.forEach(new Block<Document>() {
            public void apply(final Document document) {
                System.out.println(document);
            }
        });
        System.out.println("------------------------------------------------------");
        System.out.println();
    }
}
